<template>
  <div class="product-card" @click="handleClick">
    <div class="image-container">
      <el-image 
        :src="product.imageUrl?.startsWith('http') ? product.imageUrl : `/api${product.imageUrl}`" 
        class="product-image"
        fit="cover"
      >
        <div slot="error" class="image-slot">
          <i class="el-icon-picture-outline"></i>
        </div>
      </el-image>
      <div class="product-badge" v-if="product.isNew">新品</div>
    </div>
    
    <div class="product-content">
      <h3 class="product-name">{{ product.name }}</h3>
      
      <div class="product-info">
        <div v-if="product.isDiscount==1" class="price-section">
          <span   class="price">¥{{ product.discountPrice }}</span>
          <span  class="original-price">¥{{ product.price }}</span>

        </div>
        <div v-else class="price-section">
          <span   class="price">¥{{ product.price }}</span>
   

        </div>
        <div class="sales">已售{{ product.salesCount }}件</div>
      </div>
      
      <div class="product-actions">
        <div 
          class="cart-btn"
          @click.stop="handleAddToCart"
        >
          <i class="el-icon-shopping-cart-2"></i>
          <span>加入购物车</span>
        </div>
        <div 
          class="favorite-btn"
          :class="{ 'is-favorite': isFavoritePage || product.isFavorite }"
          @click.stop="handleFavorite"
        >
          <i :class="[isFavoritePage ? 'el-icon-delete' : 'el-icon-star-off']"></i>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Request from '@/utils/request'

export default {
  name: 'ProductCard',
  props: {
    product: {
      type: Object,
      required: true
    },
    isFavoritePage: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      userInfo: JSON.parse(localStorage.getItem('frontUser') || '{}')
    }
  },
  methods: {
    isLogin() {
      // 检查是否登录
      const userStr = localStorage.getItem('frontUser')
        if (!userStr) {
          this.$message({
            type: 'warning',
            message: '请先登录'
          })
          this.$router.push('/login')
          return false
        }
        return true
    },
    async handleAddToCart() {
      try {
   
         if(!this.isLogin()){
          return
         }

        const data = {
          userId: this.userInfo.id,
          productId: this.product.id,
          quantity: 1
        }

        const res = await Request.post('/cart', data)
        if (res.code === '0') {
          this.$message({
            type: 'success',
            message: '已添加到购物车'
          })
          this.$emit('add-to-cart', this.product)
        } else {
          this.$message({
            type: 'error',
            message: res.msg || '添加失败'
          })
        }
      } catch (error) {
        console.error('添加到购物车失败:', error)
        this.$message({
          type: 'error',
          message: '添加到购物车失败'
        })
      }
    },

    async handleFavorite() {
      try {
        // 如果是在收藏页面，只触发事件
        if (this.isFavoritePage) {
          this.$emit('toggle-favorite', this.product)
          return
        }

        if(!this.isLogin()){
          return
        }

        const data = {
          userId: this.userInfo.id,
          productId: this.product.id,
          status: this.product.isFavorite ? 1 : 0
        }
        const res = await Request.post('/favorite', data)
        if (res.code === '0') {
          // 使用服务器返回的状态
          this.product.isFavorite = res.data.status === 1
          this.$message({
            type: 'success',
            message: this.product.isFavorite ? '收藏成功' : '已取消收藏'
          })
          // 触发事件并传递最新状态
          this.$emit('toggle-favorite', {
            product: this.product,
            status: res.data.status
          })
          
          // 重新获取收藏状态
          this.getFavoriteStatus()
        } else {
          this.$message({
            type: 'error',
            message: res.msg || '操作失败'
          })
        }
      } catch (error) {
        console.error('收藏操作失败:', error)
        this.$message({
          type: 'error',
          message: '操作失败'
        })
      }
    },

    // 获取收藏状态的方法
    async getFavoriteStatus() {
      if (this.userInfo?.id) {
        try {
          const res = await Request.get(`/favorite/user/${this.userInfo.id}`)
          if (res.code === '0') {
            const favorites = res.data
            this.product.isFavorite = favorites.some(f => f.productId === this.product.id && f.status === 1)
          }
        } catch (error) {
          console.error('获取收藏状态失败:', error)
        }
      }
    },

    handleClick() {
      this.$router.push(`/product/${this.product.id}`)
    }
  },
  created() {

  },
  mounted() {
    // this.product = {
    //   ...this.product,
    //   isFavorite: false
    // }
    
    this.$nextTick(() => {
      this.getFavoriteStatus()
    })
  }
}
</script>

<style scoped>
.product-card {
  background: linear-gradient(135deg, #e8f5e9 0%, #fffde7 100%);
  border-radius: 18px;
  overflow: hidden;
  box-shadow: 0 8px 32px rgba(103,194,58,0.10);
  transition: all 0.3s ease;
  cursor: pointer;
}

.product-card:hover {
  transform: translateY(-4px) scale(1.03);
  box-shadow: 0 12px 32px rgba(103,194,58,0.16);
}

.image-container {
  position: relative;
  width: 100%;
  padding-bottom: 100%;
  overflow: hidden;
}

.product-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  transition: transform 0.3s ease;
  object-fit: cover;
}

.product-card:hover .product-image {
  transform: scale(1.05);
}

.product-badge {
  position: absolute;
  top: 12px;
  right: 12px;
  background: linear-gradient(90deg, #67c23a 60%, #a5d6a7 100%);
  color: #fff;
  padding: 4px 12px;
  border-radius: 8px;
  font-size: 13px;
  font-weight: 600;
  letter-spacing: 1px;
  box-shadow: 0 2px 8px #a5d6a733;
}

.product-content {
  padding: 16px;
}

.product-name {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  line-height: 1.4;
  margin-bottom: 8px;
}

.product-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 12px 0;
}

.price-section {
  display: flex;
  align-items: baseline;
}

.price {
  color: #43a047;
  font-size: 18px;
  font-weight: 600;
  margin-right: 8px;
}

.original-price {
  color: #999;
  font-size: 14px;
  text-decoration: line-through;
}

.sales {
  color: #666;
  font-size: 14px;
}

.product-actions {
  display: flex;
  gap: 8px;
  margin-top: 16px;
}

.cart-btn {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 8px 16px;
  border-radius: 22px;
  background: linear-gradient(135deg, #67C23A, #a5d6a7);
  color: #fff;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px #a5d6a733;
  position: relative;
  overflow: hidden;
}

.cart-btn:hover {
  background: linear-gradient(135deg, #43a047, #67c23a);
  color: #fff;
  box-shadow: 0 4px 16px rgba(103, 194, 58, 0.18);
}

.cart-btn:active {
  transform: translateY(0);
  box-shadow: 0 2px 4px rgba(103, 194, 58, 0.2);
}

.cart-btn::after {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  width: 0;
  height: 0;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  transform: translate(-50%, -50%);
  transition: width 0.3s ease, height 0.3s ease;
}

.cart-btn:active::after {
  width: 200px;
  height: 200px;
  opacity: 0;
}

.cart-btn i {
  font-size: 16px;
}

.favorite-btn {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background: #e8f5e9;
  color: #67c23a;
  cursor: pointer;
  transition: background 0.3s, color 0.3s;
  border: 1.5px solid #a5d6a7;
}

.favorite-btn:hover {
  background: #c8e6c9;
  color: #43a047;
}

.favorite-btn.is-favorite {
  color: #ff4757;
  background: #ffeaea;
  border: 1.5px solid #ffb3b3;
}

.favorite-btn.is-favorite:hover {
  background: #ffd6d6;
}

/* .image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background: #f5f7fa;
  color: #c0c4cc;
} */

@media (max-width: 700px) {
  .product-card {
    border-radius: 10px;
  }
  .product-content {
    padding: 10px;
  }
  .product-name {
    font-size: 15px;
  }
}
</style> 